package com.hb.trade.api.routine.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.hb.core.pojo.center.au.dto.UserDTO;
import com.hb.core.pojo.expert.dto.ExpertUserDTO;
import com.hb.core.pojo.expert.entity.ExpertUser;
import com.hb.trade.client.expert.ExpertClient;
import org.fzzn.core.auth.shiro.util.CredentialUtil;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.MsgUtil;
import org.springframework.stereotype.Service;

/**
 * 私有专家库登录用户信息
 *
 * @author zhaojk
 */
@Service
public class ExpertUserService {

    protected final ExpertClient expertClient;

    public ExpertUserService(ExpertClient expertClient) {
        this.expertClient = expertClient;
    }

    /**
     * 初始化私有专家帐号
     *
     * @param orgId
     * @param orgName
     * @return
     */
    public ExpertUser initExpertAccount(Long orgId, String orgName) {
        ExpertUserDTO userDTO = new ExpertUserDTO();
        userDTO.setOrgId(orgId);
        userDTO.setOrgName(orgName);

        // 生成帐号
        userDTO.generateAccount();

        // 非空字段
        userDTO.setFullName(StrUtil.EMPTY);

        // 生成密码
        String password = RandomUtil.randomString(8);
        userDTO.setPlaintextPassword(password); // 保存明文密码
        String md5Password = CredentialUtil.md5(password, UserDTO.INIT_SALT_VALUE);

        // 其他信息
        userDTO.setSaltSource(UserDTO.INIT_SALT_VALUE);
        userDTO.setPassword(md5Password);
        userDTO.setOrgName(orgName);
        userDTO.setUserStatus(1);

        return userDTO.to(new ExpertUser());
    }

    /**
     * 新增私有化专家库帐号
     * 该方法会判断指定的orgId是否已经创建私有专家库帐号
     * 如果已经创建, 不执行任何动作
     *
     * @param orgId
     * @param orgName
     * @return
     */
    public Message<Boolean> createExpertUser(Long orgId, String orgName) {
        Message<Boolean> existsMsg = expertClient.existsByOrgId(orgId);
        if (existsMsg.isSuccess() && existsMsg.getData()) {
            return MsgUtil.fail("该企业已经存在私有专家帐号");
        }

        ExpertUser expertUser = initExpertAccount(orgId, orgName);
        expertUser.buildBaseData(1);
        return expertClient.expertUserSave(expertUser);
    }

}
